package top.wshape1.shiziapi.project.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import top.wshape1.shiziapi.common.constant.RedisConstant;

import java.util.List;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-01-24
 */

public class HotProjectUtil {

    /**
     * 移除热点项目的缓存
     *
     * @param redisTemplate
     * @param projectId
     * @return
     */
    public static long removeCacheIfHot(RedisTemplate<String, Object> redisTemplate,
                                        Long projectId) {
        if (redisTemplate.opsForHash().get(RedisConstant.PROJECT_HOT_KEY + projectId,
                RedisConstant.PROJECT_HOT_NAME_KEY) != null) {
            DefaultRedisScript<Long> script = new DefaultRedisScript<>();
            script.setResultType(Long.class);
            script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/removeHotProject.lua")));
            Long execute = redisTemplate.execute(script, List.of(projectId.toString()));
            return execute == null ? 0 : execute;
        }
        return 0;
    }

    /**
     * 修改热点项目的缓存
     *
     * @param redisTemplate
     * @param projectId
     * @param field
     * @param value
     * @return
     */
    public static long updateCacheIfHot(RedisTemplate<String, Object> redisTemplate,
                                        Long projectId, String field, Object value) {
        if (redisTemplate.opsForHash().get(RedisConstant.PROJECT_HOT_KEY + projectId,
                RedisConstant.PROJECT_HOT_NAME_KEY) != null) {
            DefaultRedisScript<Long> script = new DefaultRedisScript<>();
            script.setResultType(Long.class);
            script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/updateHotProject.lua")));
            Long execute = redisTemplate.execute(script, List.of(projectId.toString(), field), value);
            return execute == null ? 0 : execute;
        }
        return 0;
    }

}
